package main

import (
	"context"
	"errors"
	"fmt"
	"gitee.com/worklz/grpc-mtls-demo/gateway/config"
	_ "gitee.com/worklz/grpc-mtls-demo/gateway/pkg/boot"
	"gitee.com/worklz/grpc-mtls-demo/gateway/pkg/global"
	"gitee.com/worklz/grpc-mtls-demo/gateway/pkg/shutdown"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// go run main.go 19100
func main() {
	// 创建通道监听操作系统信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	// 启动http服务器
	server := &http.Server{
		Addr:    config.ServerAddr,
		Handler: global.GinEngine,
	}

	// 启动http服务器
	go func() {
		fmt.Printf("http服务启动成功，监听地址: 127.0.0.1%s\r\n", config.ServerAddr)

		if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			panic(fmt.Sprintf("启动http服务异常！%v", err))
		}
	}()

	// 等待关闭信号
	<-quit

	// 优雅关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		cancel()
		log.Printf("关闭服务成功")
	}()

	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("关闭http服务异常！%v", err)
	}

	// 关闭处理
	shutdown.Handle()
}
